﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Xml;
using bmapi.HelperClass;
using bmapi.Models.CADModel;
using bmapi.Models.DataEntity;

namespace bmapi.Controllers
{
    public class CADController : BuyiController
    {
        //返回NULL，表示令牌不合法
        #region CADxml处理
        protected string ReturnError(int status, string error)
        {
            XmlDocument doc = new XmlDocument();

            XmlNode root = doc.CreateElement("return");
            doc.AppendChild(root);

            XmlElement p = doc.CreateElement("status");
            p.InnerText = status.ToString();
            root.AppendChild(p);

            p = doc.CreateElement("tip");
            p.InnerText = error;
            root.AppendChild(p);

            return ConvertXmlToString(doc);
        }
        protected string ConvertXmlToString(XmlDocument xmlDoc)
        {
            MemoryStream stream = new MemoryStream();
            XmlTextWriter writer = new XmlTextWriter(stream, System.Text.Encoding.UTF8);
            writer.Formatting = Formatting.None;
            xmlDoc.Save(writer);

            StreamReader sr = new StreamReader(stream, System.Text.Encoding.UTF8);
            stream.Position = 0;
            string xmlString = sr.ReadToEnd();
            sr.Close();
            stream.Close();
            WriteDebug("ConvertXmlToString", xmlString);
            return xmlString; //.Remove(xmlString.Length - 1);
        }
        #endregion

        
        /// <summary>
        /// 获取样式信息
        /// </summary>
        /// <param name="modelName">样式名</param>
        /// <returns></returns>
        protected string GetModelinfo(string modelName)
        {
            string sql = "select Model_tb.id as modelID, style_time, Style_tb.style_id,Style_tb.name as styleName,Style_tb.save_model from Model_tb join Style_tb on Model_tb.style_id=Style_tb.style_id where Model_tb.name=@modelName";
            XmlDocument doc = new XmlDocument();
            XmlNode root = doc.CreateElement("model");
            doc.AppendChild(root);
            try
            {
                SQLCommand sc = new SQLCommand(sql, "@modelName", modelName);
                DataTable dt = sc.ExecuteScalars();
                if (dt != null)
                {
                    XmlElement p = doc.CreateElement("status");
                    p.InnerText = "200";
                    root.AppendChild(p);

                    p = doc.CreateElement("tip");
                    p.InnerText = "OK";
                    root.AppendChild(p);

                    p = doc.CreateElement("style");
                    p.InnerText = dt.Rows[0]["styleName"].ToString();
                    root.AppendChild(p);

                    p = doc.CreateElement("root");
                    p.InnerText = dt.Rows[0]["style_time"].ToString();
                    root.AppendChild(p);

                    p = doc.CreateElement("styleID");
                    p.InnerText = dt.Rows[0]["style_id"].ToString();
                    root.AppendChild(p);

                    p = doc.CreateElement("modelID");
                    p.InnerText = dt.Rows[0]["modelID"].ToString();
                    root.AppendChild(p);

                    p = doc.CreateElement("save");
                    p.InnerText = dt.Rows[0]["save_model"].ToString();//(0普通模式，1加法模式，-1减法模式)
                    root.AppendChild(p);
                    return ConvertXmlToString(doc);
                }
                else
                {
                    XmlElement p = doc.CreateElement("status");
                    p.InnerText = "201";
                    root.AppendChild(p);

                    p = doc.CreateElement("tip");
                    p.InnerText = "failed";
                    root.AppendChild(p);
                    return ConvertXmlToString(doc);
                }
            }
            catch (Exception e)
            {
                XmlElement p = doc.CreateElement("status");
                p.InnerText = "201";
                root.AppendChild(p);

                p = doc.CreateElement("tip");
                p.InnerText = e.Message;
                root.AppendChild(p);
                return ConvertXmlToString(doc);
            }

        }

        /// <summary>
        /// 改款流程中，修改主文件
        /// </summary>
        /// <param name="loginid">工号</param>
        /// <param name="code">工序</param>
        /// <returns></returns>
        protected int EditGkMainFile(string loginid, int code)
        {
            return 0;
        }
        /// <summary>
        /// 增加日志到Task
        /// </summary> 
        /// <param name="code">工序编码</param>
        /// <param name="id">流程id</param>
        /// <returns></returns>
        protected int AddTask(int code,int id)
        {
            try
            {
                int loginid = GetCrrentIDByToken();
                if (loginid == 0) return 0;
                string sql = "insert into Task_tb values(";
                SQLCommand sc = new SQLCommand();
                sc.AddInsert("@tid", id);
                sc.AddInsert("@loginid", loginid);
                sc.AddInsert("@code", code);
                sc.AddTimeInsert("@time", DateTime.Now);
                sc.JoinSql(sql);

                int rtn = sc.ExecuteNonQuery();
                if(rtn==1)
                    WriteDebug("AddTask","Task记录新增成功");                    
                else
                    WriteDebug("AddTask", "Task记录新增失败");
                return rtn;
            }
            catch (Exception e)
            {
                WriteDebug("AddTask",e.Message);
                return 0;
            }
            
        }
        /// <summary>
        /// 大货流程中，修改主文件
        /// </summary>
        /// <param name="loginid">工号</param>
        /// <param name="code">工序</param>
        /// <returns></returns>
        protected int EditDhMainFile(string loginid, int code)
        {
            return 0;
        }
        /// <summary>
        /// 来检查两个生产单(A和B)是否具有“配套性”
        /// </summary>
        /// <param name="a">生产单A的单号</param>
        /// <param name="b">生产单B的单号</param>
        /// <returns></returns>
        protected bool IsMatching(int a, int b)
        {
            string sql = "";
            DataTable dt = new DataTable();
            List<int> alist = new List<int>();
            List<int> blist = new List<int>();
            sql = "select erp_id from LSH_tb where order_id=@orderid order by erp_id";
            SQLCommand sc = new SQLCommand(sql, "@orderid", a);
            dt = sc.ExecuteScalars();
            foreach (DataRow row in dt.Rows)
            {
                alist.Add(Convert.ToInt32(row["erp_id"]));
            }
            sc = new SQLCommand(sql, "@orderid", b);
            dt = sc.ExecuteScalars();
            foreach (DataRow row in dt.Rows)
            {
                blist.Add(Convert.ToInt32(row["erp_id"]));
            }
            if (alist.Count != blist.Count)
                return false;
            for (int i = 0; i < alist.Count; i++)
            {
                if (alist[i] != blist[i])
                    return false;
            }
            return true;
        }

        /// <summary>
        /// 修改流程标记，将上传的文件移动到流程文件夹
        /// </summary>
        /// <returns></returns>
        protected int EditMainFile()
        {
            return 0;
        }

        /// <summary>
        /// 获取下一个工序的编号(同一流水线的)  
        /// </summary>  
        /// <param name="lsx">流水线id</param>
        /// <param name="code">工序编号</param>
        /// <returns>返回0表示流程结束</returns>
        protected int GetNextProcessID(int lsx, int code)
        {
            try
            {
                string sql = "";
                if (SQLCommand.IsOracle)
                    sql = "select * from(select * from Process_tb where code > @code and PLID = @plid order by code asc) where rownum = 1";
                else
                    sql = "select top 1 code from Process_tb where code>@code and PLID=@plid order by code asc";
                WriteDebug("GetNextProcessID", "IsOracle:"+ SQLCommand.IsOracle + "当前code:"+code);
                SQLCommand sc = new SQLCommand(sql);
                sc.Add("@code", code);
                sc.Add("@plid", lsx);
                string nextcode = sc.ExecuteScalar();

                return Convert.ToInt32(nextcode);
            }
            catch (Exception e)
            {
                WriteLog("GetNextProcessID", e.Message);
                throw;
            }
        }

        /// <summary>
        /// 获取下一个工序的编号(同一流水线的)  
        /// </summary>  
        /// <param name="lsx">流水线id</param>
        /// <param name="code">工序编号</param>
        /// <returns>返回0表示流程结束</returns>
        protected Process GetNextProcess(int lsx, int code)
        {
            try
            {
                string sql = "";
                if (SQLCommand.IsOracle)
                    sql = "select * from(select * from Process_tb where code > @code and PLID = @plid order by code asc) where rownum = 1";
                else
                    sql = "select top 1 * from Process_tb where code>@code and PLID=@plid order by code asc";
                SQLCommand sc = new SQLCommand(sql);
                sc.Add("@code", code);
                sc.Add("@plid", lsx);
                return AssistFun.DataRowToObject<Process>(sc.ExecuteOneRow());
            }
            catch (Exception e)
            {
                WriteLog("GetNextProcess", e.Message);
                throw;
            }
        }

        /// <summary>
        /// 是否是我可以处理的特体的品类
        /// </summary> 
        /// <param name="loginid">工号</param>
        /// <param name="id">流程ID</param>
        /// <returns></returns>
        protected bool SuitMyPod(int loginid, int modelid)
        {
            List<string> categoryNames = GetCategoryName(loginid);            
            if (categoryNames !=null && categoryNames.Count >0 )
            {
                WriteDebug("SuitMyPod", loginid + "被指定品类,modelid:"+ modelid);
                string sql = "select type from Style_tb join Model_tb on Style_tb.style_id=Model_tb.style_id where Model_tb.id=@modelid";
                SQLCommand sc = new SQLCommand(sql, "@modelid", modelid);
                string catename = sc.ExecuteScalar();
                WriteDebug("SuitMyPod", "当前流程的品类:"+catename);
                if (categoryNames.Contains(catename))
                    return true;
                else                
                    return false;
            }
            WriteDebug("SuitMyPod", loginid + "没有指定品类，均可以处理");
            return true;
        }

        /// <summary>
        /// 判断是否是程序可处理的工序  例如：排料不可以处理打版  打版不可以处理排料  默认排料
        /// </summary>
        /// <returns> true  打版   false排料</returns>
        protected User SuitProcess(User user,bool IsPai=true)
        { 
            //此控制器用来处理 打版  将是排料的code暂时置为0 
            if (IsPai)  //排料
            {
                if (user.code != 37)
                    user.code = 0;
                if (user.code2 != 37)
                    user.code2 = 0;
                if (user.code3 != 37)
                    user.code3 = 0;
            }
            else
            {
                if (user.code == 37)
                    user.code = 0;
                if (user.code2 == 37)
                    user.code2 = 0;
                if (user.code3 == 37)
                    user.code3 = 0;
            }            
            return user;
        }

        /// <summary>
        /// 主要用于工作移交判断  若是在不关闭打版或者排料软件的情况下工作移交  可以当前的人还是可以上传  不合理
        /// </summary>
        /// <param name="code"></param>
        /// <param name="pcid"></param>
        /// <returns></returns>
        protected bool CheckIsCanFinish(int code,int pcid,int pod=0)
        {
            string sql = "";
            SQLCommand sc = null;
            try
            {
                int loginid = GetCrrentIDByToken();
                if (code == 35)
                {
                    sql = "select pod_id from Pod_tb where order_id=@pcid and pod=@pod and (user_id=@loginid or user_id=0)";
                    sc = new SQLCommand(sql);
                    sc.Add("@pcid", pcid);
                    sc.Add("@pod", pod);
                    sc.Add("@loginid", loginid);
                    if (sc.ExecuteScalar() == null)
                        return false;
                    else
                        return true;
                }
                else
                {
                    sql = "select pc_id from PC_tb where pc_id=@pcid and (station=@loginid or station=0)";
                    sc = new SQLCommand(sql);
                    sc.Add("@pcid", pcid);
                    sc.Add("@loginid", loginid);
                    if (sc.ExecuteScalar() == null)
                        return false;
                    else
                        return true;
                }
            }
            catch (Exception ex)
            {
                WriteDebug("", "异常：" + ex.Message);
                return false;
            }
            
        }
    }

}
